package com.zifeng.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zifeng.common.R;
import com.zifeng.dao.UserDao;
import com.zifeng.pojo.Ship;
import com.zifeng.pojo.User;
import com.zifeng.service.IUserService;
import com.zifeng.utils.JwtUtil;
import com.zifeng.utils.PageUtils;
import com.zifeng.utils.RedisUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.zifeng.constant.RedisConstants.*;
import static com.zifeng.utils.JwtUtil.JWT_TTL;

/**
 * 船舶用户Controller
 * 
 * @author zifeng
 * @date 2025-03-27
 */
@RestController
@RequestMapping("/user")
public class UserController
{
    @Autowired
    private IUserService userService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("count/{year}/{month}")
    public R countByMonth(@PathVariable Integer year, @PathVariable Integer month) {
        Long count = userService.countByMonth(year, month);
        return R.ok().put("count", count);
    }

    @RequestMapping("/count")
    public R count() {
        Long count = userDao.selectCount(null);
        return R.ok().put("count", count);
    }

    @RequestMapping("/listByFuzzyQuery")
    public R listByFuzzyQuery(@RequestParam Map<String, String> params) throws IOException {

        String data = params.get("data");
        if (StringUtils.isEmpty(data)) {
            return R.error(401, "查询参数不能为空");
        }
        ObjectMapper om = new ObjectMapper();
        User user = om.readValue(data, User.class);
        List<User> list = userDao.fuzzyQuery(user);
        int currPage = Integer.parseInt(params.get("page"));
        int pageSize = Integer.parseInt(params.get("limit"));
        PageUtils page = new PageUtils(list, list.size(), pageSize, currPage);

        //从第几条数据开始
        int firstIndex = (currPage - 1) * pageSize;
        //到第几条数据结束
        int lastIndex = currPage * pageSize;
        //当最后索引大于总数时，要进行设置最后索引
        if (lastIndex > page.getTotalCount()) {
            lastIndex = page.getTotalCount();
        }
        //当只有一条数据时
        if (lastIndex == firstIndex) {
            page.setList(page.getList());
        }else {
            page.setList(page.getList().subList(firstIndex, lastIndex));
        }
        System.out.println("newlist total: "+ page.getList().size());
        return R.ok().put("page", page);
    }


    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 登录
     */
    @RequestMapping("/login")
    public R login(@RequestParam String username, @RequestParam String password){
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return R.error().put("fail", "账号或密码为空");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username)
                .eq(User::getPassword, password);
        User user = userService.getOne(queryWrapper);
        if (user == null || user.getId() == 0) {
            return R.error().put("fail", "账号或密码错误");
        }
        String token = JwtUtil.createJWT(user.getId().toString(), username, null);
        redisUtils.set(LOGIN_TOKEN_KEY, token, TOKEN_TTL, TTL_TIME_UNIT);
        return R.ok().put("user", user).put("token", token);
    }


    /**
     * 获取用户详细信息
     */
    @GetMapping(value = "/{id}")
    public R getUser(@PathVariable("id") Long id)
    {
        String userKey = USER_PREFIX + id;
        User user = JSON.parseObject(redisUtils.get(userKey), User.class);
        if(user != null) return R.ok().put("user", user);
        user = userService.selectUserById(id);
        redisUtils.set(userKey, JSON.toJSONString(user));
        user = userService.selectUserById(id);
        return R.ok().put("user", user);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public R add(@RequestBody User user) {
        userService.insertUser(user);
        return R.ok();
    }

    /**
     * 修改用户
     */
    @PutMapping
    public R edit(@RequestBody User user)
    {
        userService.updateUser(user);
        return R.ok();
    }

    /**
     * 删除用户
     */
	@DeleteMapping("/{ids}")
    public R remove(@PathVariable Long[] ids)
    {
        userService.deleteUserByIds(ids);
        return R.ok();
    }
}
